package nix.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取请求参数（ a.html）
 * 
 * @author berry
 * 
 */
public class MServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		PrintWriter pw = response.getWriter();
		pw.println("<html><head><body>");

		Enumeration en = request.getParameterNames();
		while (en.hasMoreElements()) {
			response.getWriter().println(en.nextElement() + "<br/>");
		}

		String name = request.getParameter("username");
		byte[] bsName = name.getBytes("iso-8859-1");
		name = new String(bsName, "utf-8");

		response.getWriter().println(name + "<br/>");
		response.getWriter().println(request.getParameter("pwd") + "<br/>");

		Map<String, String[]> map = request.getParameterMap();
		for (String key : map.keySet()) {

			String[] values = map.get(key);
			for (int i = 0; i < values.length; i++) {
				String value = values[i];
				value = new String(value.getBytes("iso-8859-1"), "utf-8");
				values[i] = value;
			}

			response.getWriter().println(
					key + ": " + Arrays.toString(values) + "<br/>");
		}

		pw.println("</body></head></html>");
		pw.flush();
		pw.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		PrintWriter pw = response.getWriter();
		pw.println("<html><head><body>");

		Enumeration en = request.getParameterNames();
		while (en.hasMoreElements()) {
			pw.println(en.nextElement() + "<br/>");
		}

		pw.println(request.getParameter("username") + "<br/>");
		pw.println(request.getParameter("pwd") + "<br/>");
		pw.println(Arrays.toString(request.getParameterValues("hobby"))
				+ "<br/>");

		Map<String, String[]> map = request.getParameterMap();
		for (String name : map.keySet()) {
			pw.println(name + ": " + Arrays.toString(map.get(name)) + "<br/>");
		}

		pw.println("</body></head></html>");
		pw.flush();
		pw.close();
	}

}
